﻿using System;
using System.Collections.Generic;
using System.Text;
using EntityMap.Meta;
using System.Data.SqlClient;

namespace EntityMap
{
    public partial class EntityManager
    {
        public bool StoreChange<T>( string statementId, object objParameter )
        {
            bool result = false;

            using( SqlConnection conn = new SqlConnection( _connectionString ) )
            {
                EntityInfo einfo = this.GetEntityInfo( typeof( T ) );

                // get statement information
                ChangeStatement sqlStatement = einfo.GetStatement( statementId ) as ChangeStatement;

                // get map information of statement
                ParameterMap map = einfo.GetParameterMap( sqlStatement.ParameterMap );

                SqlParameter[] parameters = map.GetSqlParameters( objParameter );

                using( SqlCommand cmd = sqlStatement.GetSqlCommand( conn, parameters ) )
                {
                    conn.Open();

                    int effect = cmd.ExecuteNonQuery();

                    if( effect > 0 )
                    {
                        result = true;
                    }
                }
            }

            return result;
        }

        public bool ExecuteStored<T>( string storedId, T obj )
        {
            bool result = false;

            using( SqlConnection conn = new SqlConnection( _connectionString ) )
            {
                EntityInfo einfo = this.GetEntityInfo( typeof( T ) );

                // get statement information
                StoredProcedure stored = einfo.GetStored( storedId );

                // get map information of statement
                ParameterMap map = einfo.GetParameterMap( stored.ParameterMap );

                using( SqlCommand cmd = stored.GetSqlCommand( conn ) )
                {
                    conn.Open();

                    int effect = cmd.ExecuteNonQuery();

                    if( effect > 0 )
                    {
                        result = true;
                    }
                }
            }

            return result;
        }
    }
}
